#include"rclcpp/rclcpp.hpp"
#include"rclcpp_action/rclcpp_action.hpp"
#include"zdyac/action/zdy_act.hpp"
using zdyac::action::ZdyAct;
using namespace std::placeholders;
using GoalHandle=rclcpp_action::ClientGoalHandle<ZdyAct>;
class acclient :public rclcpp::Node{
    public:
    explicit acclient(const rclcpp::NodeOptions &node_options=rclcpp::NodeOptions()):Node("acclient",node_options){
        client_ptr=rclcpp_action::create_client<ZdyAct>(this,"get_tmp");//1创建客服端
    }
    void send_goal(int64_t num){
        if(!this->client_ptr){
            RCLCPP_ERROR(this->get_logger(),"动作客户端未初始化");
        }
        if(!this->client_ptr->wait_for_action_server(std::chrono::seconds(10))){
            RCLCPP_ERROR(this->get_logger(),"服务连接失败！");
            return ;
        }
        auto goal_msg=ZdyAct::Goal();
        goal_msg.now=num;
        RCLCPP_INFO(this->get_logger(),"发送数据");
        
        auto send_goal_options=rclcpp_action::Client<ZdyAct>::SendGoalOptions();
        send_goal_options.goal_response_callback=std::bind(&acclient::goal_response_callback,this,_1);
        send_goal_options.feedback_callback=std::bind(&acclient::feedback_callback,this,_1,_2);
        send_goal_options.result_callback=std::bind(&acclient::result_callback,this,_1);
        this->client_ptr->async_send_goal(goal_msg,send_goal_options);
        // RCLCPP_INFO(this->get_logger(),"客服端以创建");
    }
    private:
    rclcpp_action::Client<ZdyAct>::SharedPtr client_ptr;//客服端
    //处理目标发送后的反馈
    void goal_response_callback(GoalHandle::SharedPtr goal_handle){
        if(!goal_handle){
            RCLCPP_ERROR(this->get_logger(),"请求被服务器拒绝");
        }
        else {
            RCLCPP_INFO(this->get_logger(),"发送成功");
        }
    }
    //处理连续反馈
    void feedback_callback([[maybe_unused]] GoalHandle::SharedPtr goal_handle,std::shared_ptr<const ZdyAct::Feedback >feedback){
        int32_t ing=feedback->ing;
        RCLCPP_INFO(this->get_logger(),"当前温度%d",ing);
    }
    //处理结果
    void result_callback(const GoalHandle::WrappedResult &result){
        switch(result.code){
            case rclcpp_action::ResultCode::SUCCEEDED:
            break;
            case rclcpp_action::ResultCode::ABORTED:
            RCLCPP_ERROR(this->get_logger(),"任务被终止");
            break;
            case rclcpp_action::ResultCode::CANCELED:
            RCLCPP_ERROR(this->get_logger(),"任务被取消");
            return;
            default:
            RCLCPP_ERROR(this->get_logger(),"未知异常");
            return;
        }
        RCLCPP_INFO(this->get_logger(),"任务执行完毕，最终结果：%ld",result.result->final);
    }
    
};
int main(int argc,char ** argv){
    rclcpp::init(argc,argv);
    auto action_client=std::make_shared<acclient>();
    if(argc<2){
        RCLCPP_ERROR(rclcpp::get_logger("rclcpp"),"请输入一个整数");
        return 0;
    }
     int64_t num=std::stoi(argv[1]);
    action_client->send_goal(num);
    rclcpp::spin(action_client);
    rclcpp::shutdown();
    return 0;
}